package com.ds.smartstudio.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ds.smartstudio.entity.Area;
import com.ds.smartstudio.entity.Device;
import com.ds.smartstudio.mapper.AreaMapper;
import com.ds.smartstudio.mapper.DeviceMapper;
import com.ds.smartstudio.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yangsf
 * @since 2022-07-02 10:42:24
 */
@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {
    @Autowired
    AreaMapper areaMapper;
    @Autowired
    DeviceMapper deviceMapper;
    @Override
    public String areaPage(int page, int pageSize, String name) {
        Page<Area> areaPage = new Page<>(page, pageSize);
        QueryWrapper<Area> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("ds_area_id")
                .like("ds_area_name", name);
        this.page(areaPage, wrapper);
        List<Area> areas = areaPage.getRecords();
        ArrayList<Object> data = new ArrayList<>();
        data.add(areas);
        data.add(areaMapper.selectTotalByName(name));
        return JSON.toJSONString(data);
    }

    @Override
    public Integer selectTotalByName(String name) {
        return areaMapper.selectTotalByName(name);
    }

    @Override
    public boolean removeById(Area entity) {
        List<Device> devices = deviceMapper.selectList(null);
        for (Device device : devices) {
            if (Objects.equals(device.getDsAreaId(), entity.getDsAreaId())) {
                return false;
            }
        }
        return super.removeById(entity);
    }
}
